<template>
  <div class="defect-yield-container">
    <!-- Header / Search Area -->
    <!-- <div class="header-panel">
      <div class="time-selection">
        <span class="label">日 期 :</span>
        <el-date-picker
          v-model="searchParams.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          class="custom-date-picker"
          size="small"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="true"
          @change="handleDateChange"
        />
      </div>
      <div class="filter-selection">
        <span class="label">板材类型:</span>
        <el-select v-model="searchParams.plateType" placeholder="请选择" size="small" class="custom-select">
          <el-option label="内板" value="inner" />
          <el-option label="外板" value="outer" />
        </el-select>
        <span class="label" style="margin-left: 10px">用 户 :</span>
        <el-input v-model="searchParams.user" placeholder="请输入用户" size="small" class="custom-input" />
      </div>
      <div class="summary-stats"></div>
      <div class="search-actions">
        <button class="btn query-btn" @click="handleSearch">查询</button>
        <button class="btn reset-btn" @click="handleReset">重置</button>
        <button class="btn export-btn" @click="handleExport">导出</button>
      </div>
    </div> -->

    <!-- Statistics Area -->

    <!-- Table Area -->
    <div class="table-panel">
      <el-tabs v-model="tableTab" class="table-tabs">
        <el-tab-pane label="分卷优化" name="rewind"></el-tab-pane>
        <!-- <el-tab-pane label="成材率" name="yield"></el-tab-pane> -->
      </el-tabs>
      <template v-if="tableTab === 'rewind'">
        <div class="rewind-select">
          <div>
            <!-- <el-tree-select
              v-model="productionLine"
              placeholder="产线"
              multiple
              @change="fetchRewindTableData()"
              :data="productionLineOptions"
              :render-after-expand="false"
              show-checkbox
              clearable
            > -->
            <div class="search-actions">
              <span style="color: #a2cfff; font-size: 14px; margin-left: 5px">日 期 :</span>
              <el-date-picker
                v-model="searchParams.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期时间"
                end-placeholder="结束日期时间"
                class="custom-date-picker"
                size="small"
                value-format="YYYY-MM-DD"
                :clearable="true"
                @change="handleDateChange"
              />
              <span style="color: #a2cfff; font-size: 14px; margin-left: 5px">产线：</span>
              <el-select v-model="productionLine" placeholder="产线" multiple clearable @change="fetchRewindTableData()">
                <el-option v-for="item in productionLineOptions" :key="item.value" :label="item.label" :value="item" />
              </el-select>
              <button class="btn query-btn" @click="handleSearch">查询</button>
              <button class="btn reset-btn" @click="handleReset">重置</button>
              <button class="btn export-btn" @click="handleExport">导出</button>
            </div>
            <!-- </el-tree-select> -->
          </div>
        </div>
        <el-table
          :data="rewindTableData"
          ref="rewindTableRef"
          v-loading="rewindLoading"
          style="width: 100%"
          border
          size="small"
          :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '4px 8px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
          :cell-style="{ padding: '4px 8px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
          :row-class-name="rowClassName"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column prop="productionLine" label="产线" width="120" fixed="left" sortable />
          <el-table-column prop="exitCoilId" label="出口卷号" width="120" fixed="left" sortable />
          <el-table-column prop="exitWeight" label="出口重量[t]" width="120" fixed="left" />
          <el-table-column prop="orderMaxWt" label="订单重量上限[t]" width="120" />
          <el-table-column prop="orderMinWt" label="订单重量下限[t]" width="120" />
          <el-table-column prop="orderNo" label="订单号" width="120" sortable />
          <el-table-column label="重卷分切">
            <el-table-column prop="rewindExtid" label="重卷分切卷号" width="140" />
            <el-table-column prop="rewindWeight" label="分切重量[t]" width="120" />
            <el-table-column prop="rewindFlag" label="重卷分切重量异常标记" width="170">
              <template #default="{ row }">
                <span :class="['flag-text']">
                  <el-tag v-if="row.rewindFlag === '正常'" type="primary">正常</el-tag>
                  <el-tooltip v-else-if="row.rewindFlag === '超'" effect="dark" placement="top-start">
                    <template #content> 超：{{ row.rewind1Loss }} </template>
                    <el-tag type="danger">超</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.rewindFlag === '差'" effect="dark" placement="top-start">
                    <template #content> 差：{{ row.rewind1Loss }} </template>
                    <el-tag type="danger">差</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.rewindFlag === '正常(+)'" effect="dark" placement="top-start" content="需要进一步分卷">
                    <el-tag type="warning">正常(+)</el-tag>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="2#连退">
            <el-table-column prop="cal2150Extid" label="2#连退出口卷号" width="140" />
            <el-table-column prop="cal2150Weight" label="2#连退工序后卷重[t]" width="140" />
            <el-table-column prop="cal2150WtFlag" label="2#连退重量异常标记" width="150">
              <template #default="{ row }">
                <span :class="['flag-text']">
                  <el-tag v-if="row.cal2150WtFlag === '正常'" type="primary">正常</el-tag>
                  <el-tooltip v-else-if="row.cal2150WtFlag === '超'" effect="dark" placement="top-start">
                    <template #content> 超：{{ row.cal2150Loss }} </template>
                    <el-tag type="danger">超</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cal2150WtFlag === '差'" effect="dark" placement="top-start">
                    <template #content> 差：{{ row.cal2150Loss }} </template>
                    <el-tag type="danger">差</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cal2150WtFlag === '正常(+)'" effect="dark" placement="top-start" content="需要进一步分卷">
                    <el-tag type="warning">正常(+)</el-tag>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="3#连退">
            <el-table-column prop="cal1630Extid" label="3#连退出口卷号" width="140" />
            <el-table-column prop="cal1630Weight" label="3#连退工序后卷重[t]" width="140" />
            <el-table-column prop="cal1630WtFlag" label="3#连退重量异常标记" width="150">
              <template #default="{ row }">
                <span :class="['flag-text']">
                  <el-tag v-if="row.cal1630WtFlag === '正常'" type="primary">正常</el-tag>
                  <el-tooltip v-else-if="row.cal1630WtFlag === '超'" effect="dark" placement="top-start">
                    <template #content> 超：{{ row.cal1630Loss }} </template>
                    <el-tag type="danger">超</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cal1630WtFlag === '差'" effect="dark" placement="top-start">
                    <template #content> 差：{{ row.cal1630Loss }} </template>
                    <el-tag type="danger">差</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cal1630WtFlag === '正常(+)'" effect="dark" placement="top-start" content="需要进一步分卷">
                    <el-tag type="warning">正常(+)</el-tag>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="5#镀锌">
            <el-table-column prop="cgl1870Extid" label="5#镀锌出口卷号" width="140" />
            <el-table-column prop="cgl1870Weight" label="5#镀锌后卷重[t]" width="120" />
            <el-table-column prop="cgl1870WtFlag" label="5#镀锌重量异常标记" width="130">
              <template #default="{ row }">
                <span :class="['flag-text']">
                  <el-tag v-if="row.cgl1870WtFlag === '正常'" type="primary">正常</el-tag>
                  <el-tooltip v-else-if="row.cgl1870WtFlag === '超'" effect="dark" placement="top-start">
                    <template #content> 超：{{ row.cgl1870Loss }} </template>
                    <el-tag type="danger">超</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cgl1870WtFlag === '差'" effect="dark" placement="top-start">
                    <template #content> 差：{{ row.cgl1870Loss }} </template>
                    <el-tag type="danger">差</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.cgl1870WtFlag === '正常(+)'" effect="dark" placement="top-start" content="需要进一步分卷">
                    <el-tag type="warning">正常(+)</el-tag>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="3#酸轧">
            <el-table-column prop="tcm2280Extid" label="3#酸轧出口卷号" width="140" />
            <el-table-column prop="tcm2280Weight" label="3#酸轧后卷重[t]" width="120" />
            <el-table-column prop="tcm2280WtFlag" label="3#酸轧重量异常标记" width="120">
              <template #default="{ row }">
                <span :class="['flag-text']">
                  <el-tag v-if="row.tcm2280WtFlag === '正常'" type="primary">正常</el-tag>
                  <el-tooltip v-else-if="row.tcm2280WtFlag === '超'" effect="dark" placement="top-start">
                    <template #content> 超：{{ row.tcm2280Loss }} </template>
                    <el-tag type="danger">超</el-tag>
                  </el-tooltip>
                  <el-tooltip v-else-if="row.tcm2280WtFlag === '差'" effect="dark" placement="top-start">
                    <template #content> 差：{{ row.tcm2280Loss }} </template>
                    <el-tag type="danger">差</el-tag>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="hotCoilId" label="热轧卷号" width="120" />
          <el-table-column prop="hotCoilWeight" label="热轧卷重量[t]" width="120" />
          <el-table-column prop="orderThick" label="订单厚度[mm]" width="120" />
          <el-table-column prop="orderWidth" label="订单宽度[mm]" width="120" />
          <el-table-column prop="steelgrade" label="钢种代码" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
        </el-table>
        <!-- 重卷机组分页 -->
        <div class="pagination-panel">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            small
          />
        </div>
      </template>
      <template v-else>
        <div class="yield-select">
          <span style="color: #a2cfff; font-size: 14px; margin-left: 5px">产线：</span>
          <el-select v-model="selectedLine" placeholder="请选择产线" @change="handleLineChange" style="width: 160px">
            <el-option label="连退2150" value="cal2150" />
            <el-option label="连退1630" value="cal1630" />
            <el-option label="镀锌1870" value="cgl1870" />
            <el-option label="酸轧2280" value="tam2280" />
          </el-select>
        </div>
        <el-table
          :data="yieldTableData"
          style="width: 100%"
          height="100%"
          border
          highlight-current-row
          size="small"
          v-loading="yieldLoading"
          :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '4px 8px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
          :cell-style="{ padding: '4px 8px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
          :row-style="{ background: '#0f2142' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <!-- <el-table-column prop="planno" label="计划号" /> -->
          <el-table-column prop="steelgrade" label="钢牌号" />
          <el-table-column prop="exwt" label="成品重量[t]" />
          <el-table-column prop="enwt" label="原料重量[t]" />
          <el-table-column prop="yield" label="成材率">
            <template #default="{ row }"> {{ (row.yield * 100).toFixed(2) }}% </template>
          </el-table-column>
        </el-table>
        <div class="pagination-panel">
          <el-pagination
            v-model:current-page="yieldPagination.currentPage"
            v-model:page-size="yieldPagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="yieldPagination.total"
            @size-change="handleYieldSizeChange"
            @current-change="handleYieldCurrentChange"
            background
            small
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
  import * as echarts from 'echarts/core';
  import { GaugeChart, BarChart } from 'echarts/charts';
  import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import { ActualPerformanceRollDeviationApi } from '/@/api/deviationanalysis/ActualPerformanceRollDeviation';
  import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
  import { useRoute } from 'vue-router';
  import { ElMessage, ElTable } from 'element-plus';
  import dayjs from 'dayjs';
  // Register ECharts components
  echarts.use([TooltipComponent, GridComponent, LegendComponent, GaugeChart, BarChart, CanvasRenderer]);

  // --- Interfaces ---
  interface SearchParams {
    dateRange: string[];
    plateType: string;
    user: string;
  }

  interface SummaryStats {
    finishedWeight: string;
    rawWeight: string;
    yieldRate: string;
  }

  interface TableRow {
    id: number;
    hotRollNo: string;
    picklingInSub1Weight: number;
    picklingInSub2Weight: number;
    picklingExitRollNo: string;
    annealingSub1Weight: number;
    annealingSub2Weight: number;
    annealingSub3Weight: number;
    annealingExitRollNo: string;
    annealingWeight: number;
    galvanizeSub1Weight: number;
    galvanizeSub2Weight: number;
    galvanizeSub3Weight: number;
    galvanizeExitRollNo: string;
    galvanizeWeight: number;
    coverSub1Weight: number;
    coverSub2Weight: number;
    coverSub3Weight: number;
    coverRollExitNo?: string;
    coverRollWeight?: number;
    finishedWeight: number;
    rawMaterialWeight: number;
    annealingEndTime: string;
    planNo: string;
    contractNo: string;
    steelGradeLevel: string;
    copperCode: string;
    materialThickness: number;
    materialWidth: number;
    surfaceLevel: number;
    sortingLevel: number;
    mainDefectCode: string;
    orderMinWeight: number;
    orderMaxWeight: number;
    weightMismatchUnit: string;
  }

  // --- Reactive State ---
  const searchParams = reactive<SearchParams>({
    dateRange: [],
    plateType: '',
    user: '',
  });

  // 新增tab切换
  const tableTab = ref<'rewind' | 'yield'>('rewind');

  let trackIndocnos = '';

  const summary = reactive<SummaryStats>({
    finishedWeight: '3962.81',
    rawWeight: '4324.73',
    yieldRate: '91.63 %',
  });

  // 分页参数
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0,
  });

  // 重卷机组表格数据
  const rewindTableData = ref<any[]>([]);
  const rewindLoading = ref(false);
  const rewindTableRef = ref<InstanceType<typeof ElTable>>();

  const productionLine = ref([]);

  // 下拉框选项
  const productionLineOptions = ref([
    { value: 'CAL2150', label: '2#连退' }, // CAL2150连退
    { value: 'CAL1630', label: '3#连退' }, // CAL1630连退
    { value: 'TCM2280', label: '3#酸轧' }, // TCM2280酸轧
    { value: 'CGL1870', label: '5#镀锌' }, // CGL1870镀锌
    { value: 'RCL2150', label: '4#重卷' }, // CAL2150重卷
    { value: 'RCL1630', label: '5#重卷' }, // CAL1630重卷
    { value: 'RCL1870', label: '6#重卷' }, // CGL1870重卷
  ]);

  const rowClassName = ({ row }: { row: any }) => {
    const hasWarning =
      row.rewindFlag === '超' ||
      row.rewindFlag === '差' ||
      row.cal2150WtFlag === '超' ||
      row.cal2150WtFlag === '差' ||
      row.cal1630WtFlag === '超' ||
      row.cal1630WtFlag === '差' ||
      row.cgl1870WtFlag === '超' ||
      row.cgl1870WtFlag === '差' ||
      row.tcm2280WtFlag === '超' ||
      row.tcm2280WtFlag === '差';
    return hasWarning ? 'warning-row' : '';
  };

  const fetchRewindTableData = async () => {
    rewindLoading.value = true;
    try {
      let start = '',
        end = '';
      if (searchParams.dateRange && searchParams.dateRange.length === 2) {
        [start, end] = searchParams.dateRange;
      } else if (!trackIndocnos) {
        // 只有当trackIndocnos没有值时才设置默认时间
        start = dayjs().subtract(7, 'day').format('YYYY-MM-DD 00:00:00');
        end = dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
        // 更新日期选择器
        searchParams.dateRange = [start, end];
      }
      const res = await ActualPerformanceRollDeviationApi.coil_fullproc({
        page: {
          pageIndex: pagination.currentPage,
          pageSize: pagination.pageSize,
        },
        dto: {
          ...(start && end ? { startDate: start, endDate: end } : {}),
          productionLineNumber: productionLine.value.map((item: any) => item.value),
          trackIndocnos: trackIndocnos,
        },
      });
      rewindTableData.value = res?.data?.data || [];
      pagination.total = res?.data?.total || 0;
    } catch (error) {
      rewindLoading.value = false;
      ElMessage.error('获取数据失败');
    } finally {
      rewindLoading.value = false;
    }
  };

  // 分页处理函数
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    pagination.currentPage = 1;
    fetchRewindTableData();
  };

  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchRewindTableData();
  };

  // 时间选择处理函数
  const handleDateChange = () => {
    pagination.currentPage = 1;
    fetchRewindTableData();
  };

  // 查询按钮处理函数
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchRewindTableData();
  };

  // 重置按钮处理函数
  const handleReset = () => {
    searchParams.dateRange = [];
    searchParams.plateType = '';
    searchParams.user = '';
    pagination.currentPage = 1;
    fetchRewindTableData();
  };

  const handleExport = () => {
    const param = {
      page: {
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      },
    };
    try {
      ActualPerformanceRollDeviationApi.export(param);
    } catch (error: any) {
      console.error('导出Excel时出错:', error.message);
    }
  };

  // --- ECharts Refs ---
  const yieldGaugeRef = ref<HTMLElement | null>(null);
  const defectGaugeRef = ref<HTMLElement | null>(null);
  const defectBarRef = ref<HTMLElement | null>(null);
  const abnormalBarRef = ref<HTMLElement | null>(null);

  // --- ECharts Instances ---
  let yieldGaugeInstance: echarts.ECharts | null = null;
  let defectGaugeInstance: echarts.ECharts | null = null;
  let defectBarInstance: echarts.ECharts | null = null;

  // --- ECharts Options ---
  const yieldGaugeOption = computed(() => ({
    series: [
      {
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '95%',
        startAngle: 200,
        endAngle: -20,
        min: 0,
        max: 100,
        splitNumber: 5,
        progress: {
          show: true,
          width: 18,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#58D6F8' }, // Light Blue
              { offset: 1, color: '#2AF598' }, // Green
            ]),
          },
        },
        pointer: { show: false },
        axisLine: {
          lineStyle: {
            width: 18,
            color: [[1, 'rgba(44, 62, 80, 0.6)']],
          },
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        anchor: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 28,
          fontWeight: 'bold',
          offsetCenter: [0, '-5%'],
          color: '#2AF598',
          formatter: '{value}%',
        },
        data: [{ value: parseFloat(summary.yieldRate) || 0 }],
      },
    ],
  }));

  const defectGaugeOption = computed(() => ({
    tooltip: {
      formatter: '{a} <br/>{b} : {c}',
    },
    series: [
      {
        name: '缺陷统计',
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '95%',
        min: 0,
        max: 300,
        splitNumber: 6,
        axisLine: {
          lineStyle: {
            width: 15,
            color: [
              [178 / 300, '#1890FF'],
              [(178 + 38) / 300, '#FAAD14'],
              [(178 + 38 + 23) / 300, '#F5222D'],
              [1, '#D9D9D9'],
            ],
          },
        },
        pointer: { show: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        anchor: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          formatter: '{value}\n总数',
          color: '#fff',
          fontSize: 28,
          fontWeight: 'bold',
          offsetCenter: ['0', '-5%'],
        },
        data: [{ value: 242 }],
      },
    ],
  }));

  const defectBarOption = computed(() => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    grid: {
      left: '5%',
      right: '10%',
      bottom: '5%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
    },
    yAxis: {
      type: 'category',
      data: ['辊印', '夹杂', '纵向基纹', '表面其他'],
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      axisLine: { show: true, lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
      axisTick: { show: false },
    },
    series: [
      {
        name: '缺陷数量',
        type: 'bar',
        data: [3, 23, 38, 178],
        barWidth: '50%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#1890FF' },
            { offset: 1, color: '#53a8ff' },
          ]),
          borderRadius: [0, 2, 2, 0],
        },
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          fontSize: 11,
        },
      },
    ],
  }));

  // 新增异常品规柱状图option
  const abnormalBarOption = computed(() => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '10%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: abnormalTableData.value.map((item) => item.steelGrade),
      axisLabel: { color: '#c0c4cc', fontSize: 12 },
      axisLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
      axisTick: { show: false },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 12 },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.5)' } },
    },
    series: [
      {
        name: '实际值',
        type: 'bar',
        data: abnormalTableData.value.map((item) => item.actual),
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#1890FF' },
            { offset: 1, color: '#53a8ff' },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          fontSize: 12,
        },
      },
      {
        name: '目标值',
        type: 'bar',
        data: abnormalTableData.value.map((item) => item.target),
        barWidth: '40%',
        itemStyle: {
          color: '#FAAD14',
          borderRadius: [4, 4, 0, 0],
          opacity: 0.5,
        },
        label: {
          show: false,
        },
      },
    ],
  }));

  // --- ECharts Init & Update ---
  const initCharts = () => {
    try {
      if (yieldGaugeRef.value && !yieldGaugeInstance) {
        yieldGaugeInstance = echarts.init(yieldGaugeRef.value);
        yieldGaugeInstance.setOption(yieldGaugeOption.value);
      }
      if (defectGaugeRef.value && !defectGaugeInstance) {
        defectGaugeInstance = echarts.init(defectGaugeRef.value);
        defectGaugeInstance.setOption(defectGaugeOption.value);
      }
      if (defectBarRef.value && !defectBarInstance) {
        defectBarInstance = echarts.init(defectBarRef.value);
        defectBarInstance.setOption(defectBarOption.value);
      }
      // 新增异常品规柱状图
      if (abnormalBarRef.value) {
        const abnormalBarInstance = echarts.init(abnormalBarRef.value);
        abnormalBarInstance.setOption(abnormalBarOption.value);
      }
    } catch (error) {
      console.error('ECharts initialization failed:', error);
    }
  };

  const resizeCharts = () => {
    yieldGaugeInstance?.resize();
    defectGaugeInstance?.resize();
    defectBarInstance?.resize();
    if (abnormalBarRef.value) {
      echarts.getInstanceByDom(abnormalBarRef.value)?.resize();
    }
  };

  // 重卷机组数组筛选
  const filterArray = () => {
    if (productionLine.value.length == 0) return [...rewindTableData.value];
    return rewindTableData.value.filter((item) =>
      productionLine.value.some((key: any) => {
        if (!item.productionLine) return false;
        return (
          item.productionLine == key.label ||
          item.productionLine.includes(key.label) ||
          item.productionLine.toLowerCase().includes(key.label.toLowerCase())
        );
      })
    );
  };
  const route = useRoute();
  // --- Lifecycle Hooks ---
  onMounted(() => {
    const str = route.query.trackIndocnos as string;
    if (str) {
      trackIndocnos = str;
    }
    nextTick(initCharts);
    fetchRewindTableData(); // 初始加载数据
    fetchYieldData();
    window.addEventListener('resize', resizeCharts);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts);
    yieldGaugeInstance?.dispose();
    defectGaugeInstance?.dispose();
    defectBarInstance?.dispose();
  });

  // 新增异常品规表格mock数据
  interface AbnormalRow {
    steelGrade: string;
    reason: string;
    actual: number;
    target: number;
  }
  const abnormalTableData = ref<any[]>([]);

  // 成材率相关状态
  const selectedLine = ref('cal2150'); // 默认选中2#连退
  const yieldLoading = ref(false);
  const yieldTableData = ref<any[]>([]);
  const yieldPagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0,
  });

  // 获取成材率数据
  const fetchYieldData = async () => {
    yieldLoading.value = true;
    try {
      let start = '',
        end = '';
      if (searchParams.dateRange && searchParams.dateRange.length === 2) {
        [start, end] = searchParams.dateRange;
      } else if (!trackIndocnos) {
        // 只有当trackIndocnos没有值时才设置默认时间
        start = dayjs().subtract(7, 'day').format('YYYY-MM-DD 00:00:00');
        end = dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
        // 更新日期选择器
        searchParams.dateRange = [start, end];
      }

      const res = await ActualPerformanceRollDeviationApi.get_allprocessproduct({
        dbegin: start,
        dend: end,
        linename: selectedLine.value,
        pageIndex: yieldPagination.currentPage,
        pageSize: yieldPagination.pageSize,
      });

      yieldTableData.value = res?.data?.data?.allprocess || [];
      yieldPagination.total = res?.data?.count ?? res?.data?.data?.count ?? 0;
      abnormalTableData.value = res?.data?.data?.catchllprocess || [];
    } catch (error) {
      console.error('获取成材率数据失败:', error);
      ElMessage.error('获取成材率数据失败');
    } finally {
      yieldLoading.value = false;
    }
  };

  // 产线切换处理
  const handleLineChange = () => {
    yieldPagination.currentPage = 1;
    fetchYieldData();
  };

  // 成材率分页处理
  const handleYieldSizeChange = (val: number) => {
    yieldPagination.pageSize = val;
    yieldPagination.currentPage = 1;
    fetchYieldData();
  };

  const handleYieldCurrentChange = (val: number) => {
    yieldPagination.currentPage = val;
    fetchYieldData();
  };

  // 监听tab切换
  watch(tableTab, (newVal) => {
    if (newVal === 'yield') {
      fetchYieldData();
    }
  });

  watch(
    () => rewindTableData.value,
    () => {
      nextTick(() => {
        const tableRef = rewindTableRef.value;
        tableRef?.doLayout?.(); // 关键：触发表格重新渲染
      });
    },
    { deep: true }
  );
</script>

<style scoped>
  /* --- Base Styles --- */
  .defect-yield-container {
    background-color: #0a1a3a; /* Match image dark blue */
    color: #c0c4cc;
    padding: 10px; /* Consistent padding */
    height: 100vh; /* Full viewport height */
    box-sizing: border-box;
    font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
    font-size: 13px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  /* --- Header Panel --- */
  .header-panel {
    background-color: #142a52; /* Darker blue background */
    padding: 8px 15px;
    border-radius: 4px;
    margin-bottom: 10px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap; /* Allow wrapping */
    border: 1px solid #2a5caa; /* Border like image panels */
  }

  .time-selection {
    display: flex;
    align-items: center;
  }

  .time-selection .label {
    margin-right: 8px;
    white-space: nowrap;
    font-size: 13px; /* Slightly larger label */
    color: #a2cfff; /* Lighter blue label */
  }

  /* Style Date Picker like image */
  :deep(.custom-date-picker.el-date-editor) {
    width: 360px !important; /* Wider */
    height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    border-radius: 3px !important;
  }
  :deep(.custom-date-picker .el-range-input) {
    background-color: transparent !important;
    color: #a2cfff !important;
    font-size: 13px !important;
    height: 26px !important;
    line-height: 26px !important;
  }
  :deep(.custom-date-picker .el-range-separator) {
    color: #a2cfff !important;
    font-size: 13px !important;
    line-height: 26px !important;
    padding: 0 2px;
  }
  :deep(.custom-date-picker .el-input__icon) {
    line-height: 28px;
    color: #409eff; /* Use a distinct icon color */
    font-size: 13px;
  }

  .filter-selection {
    display: flex;
    align-items: center;
    margin-left: 20px; /* 增加与左侧的间距 */
  }

  .filter-selection .label {
    margin-right: 8px;
    white-space: nowrap;
    font-size: 13px;
    color: #a2cfff;
  }

  .filter-selection .custom-select,
  .filter-selection .custom-input {
    width: 120px;
    margin-right: 15px;
  }

  :deep(.custom-select .el-select__wrapper),
  :deep(.custom-input .el-input__wrapper) {
    background-color: rgba(41, 121, 255, 0.2) !important;
    border: 1px solid #42b4ff !important;
    box-shadow: 0 0 8px rgba(41, 121, 255, 0.5) !important;
    height: 22px !important;
    width: 110px;
    border-radius: 3px !important;
    transition: border-color 0.2s;
  }
  :deep(.custom-select .el-input__inner),
  :deep(.custom-input .el-input__inner) {
    height: 20px !important;
    line-height: 20px !important;
    font-size: 11px !important;
    color: #fff !important;
    padding: 0 10px;
    background: transparent !important;
  }
  :deep(.custom-select .el-select__caret) {
    font-size: 11px !important;
    color: #42b4ff;
  }
  :deep(.custom-select .el-select__placeholder),
  :deep(.custom-input .el-input__placeholder) {
    font-size: 11px !important;
    color: #a0a3a8 !important;
  }

  .summary-stats {
    display: flex;
    align-items: center;
    gap: 25px; /* Increased gap */
    font-size: 13px;
    flex-grow: 1;
    justify-content: center;
    color: #a2cfff; /* Match label color */
    margin: 5px 10px;
  }

  .summary-stats span span {
    /* Target the value part if needed */
    color: #fff; /* Make values white */
    font-weight: 500;
  }

  /* Style Buttons like image */
  .btn {
    height: 28px;
    padding: 0 18px;
    border: none;
    border-radius: 3px;
    font-size: 13px;
    cursor: pointer;
    margin-left: 10px;
    color: #fff;
    transition: background-color 0.2s ease;
  }
  .query-btn {
    background-color: #1890ff;
    box-shadow: 0 0 5px rgba(24, 144, 255, 0.5);
  }
  .query-btn:hover {
    background-color: #40a9ff;
  }
  .reset-btn {
    background-color: #5a7aa4;
    box-shadow: 0 0 5px rgba(90, 122, 164, 0.4);
  }
  .reset-btn:hover {
    background-color: #7b97c2;
  }
  .export-btn {
    background-color: #faad14;
    box-shadow: 0 0 5px rgba(250, 173, 20, 0.5);
  }
  .export-btn:hover {
    background-color: #ffc53d;
  }

  /* --- Statistics Panel --- */
  .stats-panel.new-stats-flex {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    flex-shrink: 0;
    height: 200px;
  }
  .abnormal-table-section {
    flex: 1.2;
    display: flex;
    flex-direction: column;
    background-image: url('../assets/img/itme_bg.png');
    background-size: cover;
    background-position: center;
    border: 1px solid #2a5caa;
    border-radius: 8px;
    overflow: hidden;
  }
  .abnormal-bar-section {
    flex: 1.8;
    display: flex;
    flex-direction: column;
    background-image: url('../assets/img/itme_bg.png');
    background-size: cover;
    background-position: center;
    border: 1px solid #2a5caa;
    border-radius: 8px;
    overflow: hidden;
  }
  .abnormal-table-section .chart-header,
  .abnormal-bar-section .chart-header {
    padding: 6px 15px;
    background-image: url('../assets/img/sub_title_bg.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    text-align: center;
    font-weight: bold;
    color: #a2dfff;
    font-size: 14px;
    flex-shrink: 0;
    line-height: 1.5;
  }
  .abnormal-bar-section .chart-body {
    flex: 1;
    min-height: 0;
    padding: 5px;
  }
  .abnormal-table-section .el-table {
    height: 100% !important;
  }

  /* --- Table Panel --- */
  .table-panel {
    flex-grow: 1;
    min-height: 0;
    overflow: hidden;
    background-image: url('../assets/img/itme_bg.png');
    background-size: cover;
    background-position: center;
    padding: 10px;
    border: 1px solid #2a5caa;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
  }
  .table-tabs {
    margin-bottom: 0;
    flex-shrink: 0;
  }
  .table-panel .el-tabs__content {
    padding: 0;
  }
  .table-panel .el-table {
    flex: 1 1 0%;
    min-height: 0;
    height: 100% !important;
    width: 100%;
    background: transparent;
  }

  /* --- Table Styles (Deep) --- */
  :deep(.el-table) {
    background-color: transparent !important;
  }
  :deep(.el-table th.el-table__cell) {
    background-color: #2a5caa !important; /* Header background from image */
    color: #a2dfff !important; /* Header text color */
    padding: 6px 0 !important; /* Adjust header padding */
    border-color: #06279d !important;
    font-weight: normal !important;
    text-align: center;
  }
  :deep(.el-table td.el-table__cell) {
    padding: 5px 0 !important; /* Adjust cell padding */
    border-color: #06279d !important;
    text-align: center;
    font-size: 12px; /* Smaller font */
    color: #c0c4cc;
  }
  :deep(.el-table tr) {
    background-color: transparent !important; /* Ensure row itself is transparent */
  }
  :deep(.el-table__body tr:nth-child(odd)) {
    background-color: #0f2142 !important; /* Dark blue odd rows */
  }
  :deep(.el-table__body tr:nth-child(even)) {
    background-color: #142a52 !important; /* Lighter blue even rows */
  }
  :deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
    /* background-color: inherit !important; */ /* Remove no hover effect */
    background-color: rgba(66, 180, 255, 0.15) !important; /* Apply semi-transparent blue on hover */
  }

  /* Apply same style to current selected row */
  :deep(.el-table__body tr.current-row > td.el-table__cell) {
    background-color: rgba(66, 180, 255, 0.15) !important;
  }

  /* Borders */
  :deep(.el-table--border .el-table__inner-wrapper::after),
  :deep(.el-table--border::after),
  :deep(.el-table--border::before) {
    background-color: #06279d !important;
  }
  :deep(.el-table td.el-table__cell),
  :deep(.el-table th.el-table__cell.is-leaf) {
    border-bottom: 1px solid #06279d !important;
  }
  :deep(.el-table--border td.el-table__cell),
  :deep(.el-table--border th.el-table__cell) {
    border-right: 1px solid #06279d !important;
  }
  :deep(.el-table__border-left-patch) {
    background-color: #06279d !important;
  }
  :deep(.el-table .el-table__cell) {
    border-color: #06279d !important; /* General border color */
    color: #fff !important;
  }
  :deep(.el-table--border) {
    border: 1px solid #06279d !important; /* Ensure outer border color */
  }
  :deep(.el-table:before) {
    /* Hide default bottom border line */
    display: none;
  }

  /* --- Pagination Panel --- */
  .pagination-panel {
    background-color: #142a52;
    padding: 8px 15px;
    border-radius: 4px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 10px;
    border: 1px solid #2a5caa;
  }
  /* Deep pagination styles */
  :deep(.el-pagination) {
    --el-pagination-bg-color: transparent;
    --el-pagination-text-color: #c0c4cc;
    --el-pagination-button-disabled-bg-color: transparent;
    --el-pagination-button-bg-color: transparent;
    --el-pagination-hover-color: #409eff;
  }
  :deep(.el-pager li) {
    border: 1px solid #2a5caa;
    margin: 0 3px;
    border-radius: 3px;
    min-width: 24px;
    height: 24px;
    line-height: 22px;
    font-size: 12px;
  }
  :deep(.el-pager li) {
    background-color: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }
  :deep(.el-pagination button) {
    border: 1px solid #2a5caa;
    margin: 0 3px;
    border-radius: 3px;
    min-width: 24px;
    height: 24px;
    padding: 0 6px;
  }
  :deep(.el-pagination button:disabled) {
    border-color: #2a5caa;
    opacity: 0.5;
  }
  :deep(.el-pagination__jump) {
    color: #c0c4cc;
    margin-left: 10px;
    font-size: 13px;
  }
  :deep(.el-pagination__jump .el-input__wrapper) {
    background: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    height: 24px;
    width: 40px;
    border-radius: 3px;
    padding: 0 3px;
  }
  :deep(.el-pagination__jump .el-input__inner) {
    color: #c0c4cc !important;
    height: 22px !important;
    line-height: 22px !important;
    text-align: center;
    font-size: 12px !important;
  }
  :deep(.el-pagination__total) {
    color: #c0c4cc;
    margin-right: 10px;
    font-size: 13px;
  }
  :deep(.el-pagination__sizes) {
    margin-right: 10px;
  }
  :deep(.el-pagination__sizes .el-select .el-input__wrapper) {
    background: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    height: 24px;
    width: 90px;
    border-radius: 3px;
    padding: 0 3px;
  }
  :deep(.el-pagination__sizes .el-select .el-input__inner) {
    color: #c0c4cc !important;
    height: 22px !important;
    line-height: 22px !important;
    font-size: 12px !important;
  }
  :deep(.el-pagination .el-select__caret) {
    color: #409eff;
  }

  /* 板材类型下拉框弹出菜单深色 */
  :deep(.el-select-dropdown) {
    background-color: #142a52 !important;
    border: 1px solid #2a5caa !important;
  }
  :deep(.el-select-dropdown__item) {
    color: #a2cfff !important;
    background-color: #142a52 !important;
  }
  :deep(.el-select-dropdown__item.selected) {
    background-color: #1890ff !important;
    color: #fff !important;
  }
  :deep(.el-select-dropdown__item.hover) {
    background-color: #1e3a6d !important;
    color: #fff !important;
  }

  /* 分页下拉框深色 */
  :deep(.el-pagination__sizes .el-select-dropdown) {
    background-color: #142a52 !important;
    border: 1px solid #2a5caa !important;
  }
  :deep(.el-pagination__sizes .el-select-dropdown__item) {
    color: #a2cfff !important;
    background-color: #142a52 !important;
  }
  :deep(.el-pagination__sizes .el-select-dropdown__item.selected) {
    background-color: #1890ff !important;
    color: #fff !important;
  }
  :deep(.el-pagination__sizes .el-select-dropdown__item.hover) {
    background-color: #1e3a6d !important;
    color: #fff !important;
  }

  .table-tabs :deep(.el-tabs__item) {
    color: #a2dfff;
    font-size: 14px;
    font-weight: bold;
    height: 36px;
    line-height: 36px;
    transition: color 0.2s;
  }
  .table-tabs :deep(.el-tabs__item.is-active) {
    color: #fff !important;
    background: none;
  }
  .table-tabs :deep(.el-tabs__active-bar) {
    background-color: #1890ff !important;
    height: 3px;
    border-radius: 2px 2px 0 0;
  }

  /* 异常标记样式 */
  .flag-text {
    padding: 2px 8px;
    border-radius: 2px;
    font-weight: 500;
  }

  .flag-text.normal {
    color: #67c23a;
    background-color: rgba(103, 194, 58, 0.1);
  }

  .flag-text.abnormal {
    color: #f56c6c;
    background-color: rgba(245, 108, 108, 0.1);
  }

  .rewind-select {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    span {
      /* color: red; */
      font-size: 10px;
    }

    .el-select {
      width: auto;
      min-width: 180px;
    }

    :deep(.el-select .el-select__wrapper) {
      background-color: rgba(41, 121, 255, 0.2) !important;
      border: 1px solid #42b4ff !important;
      box-shadow: 0 0 8px rgba(41, 121, 255, 0.5) !important;
      height: 22px !important;
      width: auto !important;
      border-radius: 3px !important;
      transition: border-color 0.2s;
    }
    :deep(.el-select .el-input__inner) {
      height: 20px !important;
      line-height: 20px !important;
      font-size: 11px !important;
      color: #fff !important;
      padding: 0 10px;
      background: transparent !important;
    }
    :deep(.el-select .el-select__caret) {
      font-size: 11px !important;
      color: #42b4ff;
    }
    :deep(.el-select .el-select__placeholder) {
      font-size: 11px !important;
      color: #a0a3a8 !important;
    }
    :deep(.el-select:hover .el-select__selected-item) {
      /* background-color: #42b4ff !important; */
      background-color: transparent !important;
    }
  }

  :deep(.el-table) {
    --el-table-row-hover-bg-color: unset;
    --el-table-border-color: transparent;
  }

  :deep(.el-table-fixed-column--left) {
    background-color: rgba(66, 180, 255, 0.15) !important; /* Apply semi-transparent blue on hover */
  }

  :deep(.el-table__body .el-table-fixed-column--left:nth-child(odd)) {
    background-color: #0f2142 !important; /* Dark blue odd rows */
  }
  :deep(.el-table__body .el-table-fixed-column--left:nth-child(even)) {
    background-color: #142a52 !important; /* Lighter blue even rows */
  }

  /* 成材率产线选择样式 */
  .yield-select {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .yield-select :deep(.el-select .el-select__wrapper) {
    background-color: rgba(41, 121, 255, 0.2) !important;
    border: 1px solid #42b4ff !important;
    box-shadow: 0 0 8px rgba(41, 121, 255, 0.5) !important;
    height: 22px !important;
    width: auto !important;
    border-radius: 3px !important;
    transition: border-color 0.2s;
  }
  :deep(.el-select .el-input__inner) {
    height: 20px !important;
    line-height: 20px !important;
    font-size: 11px !important;
    color: #fff !important;
    padding: 0 10px;
    background: transparent !important;
  }
  :deep(.el-select .el-select__caret) {
    font-size: 11px !important;
    color: #42b4ff;
  }
  :deep(.el-select .el-select__placeholder) {
    font-size: 11px !important;
    color: #a0a3a8 !important;
  }
  :deep(.el-select:hover .el-select__selected-item) {
    /* background-color: #42b4ff !important; */
    background-color: transparent !important;
  }

  .el-table__fixed .warning-row td {
    background-color: #966 !important;
  }

  :deep(.el-table .warning-row td) {
    background-color: #966 !important;
    color: #fff !important;
  }

  :deep(.el-table__body .warning-row .el-table-fixed-column--left) {
    background-color: #966 !important;
  }

  :deep(.el-table__fixed, .el-table-fixed-column--left) {
    background-color: transparent !important;
  }
</style>
